package mysql

import (
	"fmt"
	"math/rand"
	"msems/models"
	"time"

	"go.uber.org/zap"

	"golang.org/x/crypto/bcrypt"
)

// CheckUserExist 判断指定用户是否存在
func CheckUserExist(username string) (err error) {
	sqlStr := `select count(id) from admin_user where username = ?`
	var count int
	if err = db.Get(&count, sqlStr, username); err != nil {
		return err
	}
	if count > 0 {
		return ErrorUserExist
	}
	return
}

// InsertUser 插入一条新的管理员数据
func InsertUser(user *models.User) error {
	// 对密码进行加密
	hash, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost) //加密处理
	if err != nil {
		fmt.Printf("bcrypt.GenerateFromPassword err:%v", err)
		return err
	}
	//防止跳id

	sqlStr := "ALTER TABLE `admin_user` AUTO_INCREMENT =1"
	_, err = db.Exec(sqlStr)
	if err != nil {
		return err
	}
	// 执行sql语句入库
	sqlStr = `insert into admin_user(username, password) values(?,?)`
	_, err = db.Exec(sqlStr, user.Username, string(hash))
	if err != nil {
		zap.L().Error("db.Exec(sqlStr, user.UserID, user.Username, string(hash))", zap.Error(err))
		return err
	}
	return nil
}

// AdminLoginUser LoginUser 管理员账号密码验证
func AdminLoginUser(user *models.User) (err error) {
	sqlStr := "select id,username,password,level,email from admin_user where username=?"
	password := user.Password
	//取出密码
	if err = db.Get(user, sqlStr, user.Username); err != nil {
		return ErrorUserNotExist
	}
	//密码验证
	err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
	return err
}

// AdminSendEmail 管理员验证邮箱和账号
func AdminSendEmail(p *models.AdminEmail, user *models.User) (err error) {
	sqlStr := `select email from admin_user where username=?`
	if err = db.Get(user, sqlStr, p.Username); err != nil {
		return ErrorEmaiNotExist
	}
	if user.Email != p.Email {
		return ErrorEmaiNotExist
	}
	return
}

// EmailCode 新建验证码
func EmailCode(email, username string) (code string, err error) {
	code = fmt.Sprintf("%04v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(10000)) //这里面前面的04v是和后面的1000相对应的
	// 当前用户如果之前有状态为1没用过的将状态置为0
	sqlStr := "update s_email set status=0 where email=? and username=? and status=1"
	_, err = db.Exec(sqlStr, email, username)
	if err != nil {
		err = nil
	}
	//防止跳id
	sqlStr = "ALTER TABLE `s_email` AUTO_INCREMENT =1"
	_, err = db.Exec(sqlStr)
	if err != nil {
		return "", err
	}
	// 执行sql语句入库
	sqlStr = `insert into s_email(username,email, code) values(?,?,?)`
	_, err = db.Exec(sqlStr, username, email, code)
	if err != nil {
		return "", ErrorEmaiNotExist
	}
	return
}

// AdminCode 验证用户和验证码
func AdminCode(p *models.AdminCode) (err error) {
	codeModel := new(models.CodeModel)
	sqlStr := `select code,email,status,create_time from s_email where email=? and username=? and status=1`
	if err = db.Get(codeModel, sqlStr, p.Email, p.Username); err != nil {
		return ErrorCodeNotExist
	}
	if codeModel.Code != p.Code {
		return ErrorCodeNotExist
	}
	return
}

// AdminInsertUser 插入一条新的管理员数据
func AdminInsertUser(user *models.User) error {
	// 对密码进行加密
	hash, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost) //加密处理
	if err != nil {
		fmt.Printf("bcrypt.GenerateFromPassword err:%v", err)
		return err
	}
	// 执行sql语句入库
	sqlStr := `insert into admin_user(username, password,email,class_id,teacher_id,college_id,level) values(?,?,?,?,?,?,?)`
	_, err = db.Exec(sqlStr, user.Username, string(hash), user.Email, user.ClassID, user.TeacherID, user.CollegeID, user.Level)
	if err != nil {
		zap.L().Error("db.Exec(sqlStr, user.UserID,"+
			" user.Username, string(hash))",
			zap.Error(err))
		return err
	}
	return nil
}

//// 修改密码
//func AdminChangeP(p *models.AdminCode) (err error) {
//	// 对密码进行加密
//	hash, err := bcrypt.GenerateFromPassword([]byte(p.Password), bcrypt.DefaultCost) //加密处理
//	if err != nil {
//		fmt.Printf("bcrypt.GenerateFromPassword err:%v", err)
//		return err
//	}
//	sqlStr := "update admin_user set password=? where username=?"
//	_, err = db.Exec(sqlStr, string(hash), p.Username)
//	if err != nil {
//		zap.L().Error("db.Exec(sqlStr, string(hash), p.Username)", zap.Error(err))
//		return ErrorUserNotExist
//	}
//	var email string
//	sqlStr = `select email from admin_user where username=?`
//	if err = db.Get(&email, sqlStr, p.Username); err != nil {
//		return ErrorEmaiNotExist
//	}
//	sqlStr = "update s_email set status=0 where email=? and username=? and status=1"
//	_, err = db.Exec(sqlStr, email, p.Username)
//	if err != nil {
//		err = nil
//	}
//	return
//}

// AdminChangeP 修改密码
func AdminChangeP(p *models.ParamSignUp) (err error) {
	// 对密码进行加密
	hash, err := bcrypt.GenerateFromPassword([]byte(p.Password), bcrypt.DefaultCost) //加密处理
	if err != nil {
		fmt.Printf("bcrypt.GenerateFromPassword err:%v", err)
		return err
	}
	sqlStr := "update admin_user set password=? where username=?"
	_, err = db.Exec(sqlStr, string(hash), p.Username)
	if err != nil {
		zap.L().Error("db.Exec(sqlStr, string(hash), p.Username)", zap.Error(err))
		return ErrorUserNotExist
	}
	var email string
	sqlStr = `select email from admin_user where username=?`
	if err = db.Get(&email, sqlStr, p.Username); err != nil {
		return ErrorEmaiNotExist
	}
	sqlStr = "update s_email set status=0 where email=? and username=? and status=1"
	_, err = db.Exec(sqlStr, email, p.Username)
	if err != nil {
		err = nil
	}
	return
}
